import { Link, useHistory, useModel } from 'umi';
import { Form, Input, Modal, Popconfirm, Popover } from 'antd';
import styles from './index.less';
import classNames from 'classnames';
import sScore from './icon-s.png';
import asScore from './icon-a+.png';
import aScore from './icon-a.png';
import bScore from './icon-b.png';
import VideoPlayerModal from '../VideoPlayer';
import { useEffect, useState } from 'react';
import { allGet } from '@/services/pc';
import AuthModal from '../AuthModal';
import ZModal from '../ZModal';

const PersonDetail = (props) => {
  const [data, setData] = useState<any>({});
  useEffect(() => {
    (async () => {
      const response = await allGet({
        params: {
          mod: 'busywork',
          do: 'list',
          uid: props?.uid,
          perpage: 3,
          page: 1,
          version: 'pc1.0',
        },
      });
      setData(response);
    })();
  }, []);
  return (
    <Link to={`/personal?uid=${props?.uid}`} onClick={(e) => e.stopPropagation()}>
      <div className={styles.header}>
        <i className={styles.avatar} style={{ backgroundImage: `url(${props?.avatar})` }} />
        <div className={styles.right}>
          <div className={styles.nick}>{props?.username}</div>
          <div className={styles.message}>{props?.user}</div>
        </div>
      </div>
      <div className={styles.main}>
        {data?.data?.list?.length > 0 && (
          <div className={styles.list}>
            {data?.data?.list?.map((item) => (
              <div
                key={item.bid}
                className={styles.item}
                style={{ backgroundImage: `url(${item?.pic})` }}
              >
                <div className={styles.footer}>
                  <img
                    loading="lazy"
                    className={styles.icon}
                    src={require('@/assets/pc/images/index/star.png')}
                  />
                  <span className={styles.num}>{item?.goodnum || 0}</span>
                </div>
              </div>
            ))}
          </div>
        )}
        {/* <div className={styles.item} style={{ backgroundImage: "url(https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg)" }}>
          <div className={styles.footer}>
            <img loading="lazy" className={styles.icon} src={require('@/assets/pc/images/index/star.png')} />
            <span className={styles.num}>764</span>
          </div>
        </div>
        <div className={styles.item} style={{ backgroundImage: "url(https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg)" }}>
          <div className={styles.footer}>
            <img loading="lazy" className={styles.icon} src={require('@/assets/pc/images/index/star.png')} />
            <span className={styles.num}>764</span>
          </div>
        </div> */}
      </div>
    </Link>
  );
};

interface WorksItemProps {
  index: number;
  type?: 'img' | 'video';
  columns?: number;
  personId?: any;
  className?: string;
  onClick?: (index, e?: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
  onEdit?: (index, e?: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;

  isLink?: boolean;
  link?: string;
  /**
   * 1 首页那种没分数，带课程标题的
   * 2 就显示S分数，带课程标题的
   * 3 批改作业，不显示分数，  带学号的
   * 4 显示所有分数，带学号的
   * 5 学生编辑作业,带课程标题的
   * 6 显示所有分数，带课程标题的
   * 7 学员中心， 带所有分数，能编辑删除的
   */
  itemType?: 1 | 2 | 3 | 4 | 5 | 6 | 7;
  hasWorkTitle?: boolean; // 是否有作业标题
  handleDeleteOK?: (index) => void;
}
export const WorksItem: React.FC<WorksItemProps> = ({
  index,
  type = 'img',
  personId,
  columns,
  itemType = 1,
  className,
  onClick,
  isLink = true,
  link = '',
  onEdit,
  hasWorkTitle = false,
  ...props
}) => {
  const history = useHistory();
  const [deleteForm] = Form.useForm();
  const { userInfo } = useModel('user');
  const anyProps = props as any;
  const [deleteVisible, setDeleteVisible] = useState(false);
  const [deleteVisible2, setDeleteVisible2] = useState(false);
  const handleClick = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
    e.preventDefault();
    onClick?.(index, e);
  };
  const handleEdit = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
    e.stopPropagation();
    onEdit?.(index, e);
  };
  const handleDelete = async (e) => {
    e.stopPropagation();
    if (itemType === 7) {
      return setDeleteVisible2(true);
    }
    setDeleteVisible(true);
  };
  const [deleteLoading, setDeleteLoading] = useState(false);
  const handleDeleteOK = async () => {
    try {
      if (deleteLoading) return;
      setDeleteLoading(true);
      const response = await allGet({
        params: {
          mod: 'busywork',
          bid: anyProps.bid,
          do: 'delete',
          version: 'pc1.0',
        },
      });
      if (response.success) {
        anyProps.handleDeleteOK?.(index);
        setDeleteVisible(false);
      }
    } catch (error) {
      console.log(error);
    } finally {
      setDeleteLoading(false);
    }
  };
  const handleNewEdit = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
    e.stopPropagation();
    history.push(
      `/center/upload/work?lid=${anyProps?.lid}&bid=${anyProps?.bid}&classid=${anyProps.classid}`,
    );
  };

  /**
   * ie的 grid布局
   */
  // let style = {};
  // if (columns) {
  //   style = msGridColRow({ columns, index })
  // }
  const score = () => {
    if (itemType === 2 && anyProps?.score === 4)
      return <img loading="lazy" className="cgjoy--works-item-score" src={sScore} alt="" />;
    if (itemType === 4 || itemType === 6 || itemType === 7) {
      /**
       * @todo
       * 根据分数来换图片
       */
      if (anyProps.score === 4) {
        return <img loading="lazy" className="cgjoy--works-item-score" src={sScore} alt="" />;
      }
      if (anyProps.score === 3) {
        return <img loading="lazy" className="cgjoy--works-item-score" src={asScore} alt="" />;
      }
      if (anyProps.score === 2) {
        return <img loading="lazy" className="cgjoy--works-item-score" src={aScore} alt="" />;
      }
      if (anyProps.score === 1) {
        return <img loading="lazy" className="cgjoy--works-item-score" src={bScore} alt="" />;
      }
      return null;
    }
    return null;
  };
  const showDelete = () => {
    if (!userInfo.uid) return false;
    if (itemType === 3) return false;
    // 需要显示管理员操作的
    if (anyProps.hasAdminAction && userInfo.isadmin == 1) {
      return true;
    }
    if (itemType === 7 && anyProps.uid == userInfo.uid && anyProps.score == 0) {
      return true;
    }
    return false;
  };

  const showEdit = () => {
    if (!userInfo.uid) return false;
    if (itemType === 3) return false;
    return anyProps.score == 0;
  };
  const content = (
    <div className="cgjoy--works-item-ratio" onClick={handleClick}>
      <div className="cgjoy--works-item-content">
        <img
          loading="lazy"
          className="cgjoy--works-item-img"
          src={anyProps.thumb}
          alt={anyProps.subject}
        />
        {/* {type === 'video' && itemType !== 3 && itemType !== 5 && <div className="cgjoy--works-item-mask" >
        <i className="cgjoy--works-item-icon_play" />
      </div>}
      {type === 'img' && itemType !== 3 && itemType !== 5 && <div className="cgjoy--works-item-mask" >
      </div>} */}
        {score()}
        {!showDelete() && !showEdit() && <i className="cgjoy--works-item-mask" />}
        {(showDelete() || showEdit()) && (
          <div className="cgjoy--works-item-admin-action">
            {showEdit() && (
              <div className="cgjoy--works-item-admin-action-edit" onClick={handleNewEdit}>
                编辑
              </div>
            )}
            {showDelete() && (
              <div className="cgjoy--works-item-admin-action-del" onClick={handleDelete}>
                删除
              </div>
            )}
          </div>
        )}
        {itemType === 3 && (
          <div className="cgjoy--works-item-pigai">
            <i className="cgjoy--works-item-pigai_icon" />
            批改
          </div>
        )}
        {itemType === 5 && (
          <div className="cgjoy--works-item-pigai" onClick={handleEdit}>
            <i className="cgjoy--works-item-pigai_icon" />
            编辑
          </div>
        )}
      </div>
    </div>
  );
  const title = () => {
    if (itemType === 1 || itemType == 2 || itemType == 5 || itemType == 6 || itemType == 7) {
      return anyProps.classname;
    }
    return (
      <div className={styles.xuehao}>
        <span>{`学号：${anyProps.studentnum}`}</span>
      </div>
    );
  };
  const handleClickTitle = (e) => {
    e.stopPropagation();
    if (itemType === 1 || itemType == 2 || itemType == 5 || itemType == 6 || itemType == 7) {
      window.open(`/center/courses/detail/${anyProps.classid}`);
    }
  };

  const handleClickNick = (e) => {
    e.stopPropagation();
    window.open(`/personal?uid=${anyProps.uid}`);
  };

  return (
    <div
      className={classNames(styles['cgjoy--works-item'], 'cgjoy--works-item', className, {
        hasWorkTitle,
      })}
    >
      {isLink ? <Link to={link}>{content}</Link> : <div className={styles.content}>{content}</div>}
      {hasWorkTitle && (
        <div className="cgjoy--works-item-work-title" onClick={handleClick}>
          <div className="text">{anyProps?.subject}</div>{' '}
        </div>
      )}
      <div className={classNames('cgjoy--works-item-des')}>
        {itemType != 7 && (
          <div className="cgjoy--works-item-des_left">
            {/* <Popover
            overlayClassName={classNames(
              'cgjoy--works-item-person',
              styles['cgjoy--works-item-person'],
            )}
            placement="right"
            trigger="click"
            content={<PersonDetail {...props} />}
            title={() => null}
          >
            {anyProps.avatar && (
              <i
                className="cgjoy--works-item-avatar"
                style={{ backgroundImage: `url(${anyProps.avatar})` }}
              />
            )}
          </Popover> */}
            <i
              className="cgjoy--works-item-avatar"
              style={{ backgroundImage: `url(${anyProps.avatar})` }}
              onClick={handleClickNick}
            />
            <div className="cgjoy--works-item-nick" onClick={handleClickNick}>
              {anyProps.username}
            </div>
          </div>
        )}
        {itemType == 7 ? (
          <div
            className={classNames(
              'cgjoy--works-item-title-new',
              'cgjoy--works-item-title-new-classnamehover',
            )}
            onClick={handleClickTitle}
          >
            <div className="cgjoy--works-item-title-new-text">{anyProps.classname}</div>
            <div className="cgjoy--works-item-title-new-arrow" />
          </div>
        ) : (
          <div
            className={classNames('cgjoy--works-item-title', {
              'cgjoy--works-item-title_hover':
                itemType === 1 || itemType == 2 || itemType == 5 || itemType == 6,
            })}
            onClick={handleClickTitle}
          >
            {title()}
          </div>
        )}
      </div>

      <Modal
        centered
        destroyOnClose
        className={styles.deleteModal}
        visible={deleteVisible}
        width={390}
        footer={null}
        onCancel={() => setDeleteVisible(false)}
        maskClosable
      >
        <div className={styles.title}>填写删除原因</div>
        <Form
          form={deleteForm}
          initialValues={{ type: [1] }}
          scrollToFirstError
          className={styles.form}
          layout="vertical"
          name="basic"
          autoComplete="off"
          validateTrigger={false}
        >
          <Form.Item
            label=""
            name="reason"
            rules={[{ required: true, message: '请填写删除该作品原因' }]}
          >
            <Input.TextArea className={styles.textarea} placeholder="请填写删除该作品原因" />
          </Form.Item>
        </Form>
        <div className={styles.footer}>
          <div className={styles.btn} onClick={handleDeleteOK}>
            删除
          </div>
          <div
            className={classNames(styles.btn, styles.cancel)}
            onClick={() => setDeleteVisible(false)}
          >
            取消
          </div>
        </div>
      </Modal>

      <Modal
        destroyOnClose
        className={styles.deleteModal2}
        visible={deleteVisible2}
        width={390}
        centered
        footer={null}
        onCancel={() => setDeleteVisible(false)}
        maskClosable
      >
        <div className={styles.title}>删除作业</div>
        <div className={styles.tips}>是否要删除该作业？</div>
        <div className={styles.footer}>
          <div className={styles.btn} onClick={handleDeleteOK}>
            删除
          </div>
          <div
            className={classNames(styles.btn, styles.cancel)}
            onClick={() => setDeleteVisible2(false)}
          >
            取消
          </div>
        </div>
      </Modal>
    </div>
  );
};

// 我喜欢的课程的小的item
export const WorksItemSmall = ({ data, onClick = () => null as any }) => {
  const type = data.video ? 'video' : 'img';

  return (
    <div
      className={classNames(
        styles['cgjoy--works-item-small'],
        'cgjoy--works-item-small',
        styles[type],
      )}
      onClick={onClick}
    >
      <div className={styles.img} style={{ backgroundImage: `url(${data.pic})` }} />
      {type === 'video' && (
        <div className={styles.video}>
          <i className={styles.icon_play} />
        </div>
      )}
      <div className={styles.star}>
        <img
          loading="lazy"
          className={styles.icon}
          src={require('@/assets/pc/images/index/star.png')}
        />
        1245
      </div>
      {/* <div className={styles.imgwrapper}>
      
    </div> */}
      {/* <i className={styles.hoverborder} /> */}
    </div>
  );
};

interface WorksProps {
  data: any[];
  itemKey: string;
  columns?: number;
}

const Works: React.FC<WorksProps> = ({ data = [], itemKey, columns = 5 }) => {
  const handleClick = (index, e) => {
    VideoPlayerModal.showStar({
      data: data.map((item) => ({ ...item, url: item.video || item.pic })),
      defaultIndex: index,
    });
  };
  return (
    <div className={classNames('cgjoy--works', styles['cgjoy--works'])}>
      {data.map((item, index) => (
        <WorksItem
          columns={columns}
          key={item[itemKey]}
          index={index}
          type={item.video ? 'video' : 'img'}
          onClick={handleClick}
          {...item}
        />
      ))}
    </div>
  );
};
export default Works;
